package jmine.tec.web.wicket.component;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;

import jmine.tec.web.wicket.component.table.SelectEntityModel;

import org.apache.wicket.markup.html.form.Check;

/**
 * CheckGroup que não depende que os checkboxes sejam seus "filhos" na hierarquia.
 * 
 * @author Rafael Volpato
 * @date Oct 1, 2011
 */
public class CheckGroup extends org.apache.wicket.markup.html.form.CheckGroup<Serializable> {

    private final List<Check<SelectEntityModel>> checks;

    /**
     * Construtor.
     * 
     * @param id id chosen
     * @param chosen checks
     * @param checks check boxes
     */
    public CheckGroup(String id, Set<Serializable> chosen, List<Check<SelectEntityModel>> checks) {
        super(id, chosen);

        this.checks = checks;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected Collection<Serializable> convertValue(String[] values) {
        List<Serializable> collection = new ArrayList<Serializable>();

        if (values != null && values.length > 0) {
            for (int i = 0; i < values.length; i++) {
                final String value = values[i];

                if (value != null) {
                    for (Check<SelectEntityModel> check : this.checks) {
                        if (String.valueOf(check.getValue()).equals(value)) {
                            collection.add(check.getModelObject().getPrimaryKey());
                            break;
                        }
                    }
                }
            }
        }

        return collection;
    }
}
